import sys, argparse

## import Twisted reactor
##
if sys.platform == 'win32':
   ## on windows, we need to use the following reactor for serial support
   ## http://twistedmatrix.com/trac/ticket/3802
   ##
   from twisted.internet import win32eventreactor
   win32eventreactor.install()   


from MyApplication import McuComponent

if __name__ == '__main__':


   ## parse command line arguments
   ##
   parser = argparse.ArgumentParser()

   parser.add_argument("-d", "--debug", action = "store_true",
                       help = "Enable debug output.")

   parser.add_argument("--baudrate", type = int, default = 115200, choices = [300, 1200, 2400, 4800, 9600, 19200, 57600, 115200],
                       help = 'Serial port baudrate.')

   parser.add_argument("--port", type = str, default = 'COM4',
                       help = 'Serial port to use (e.g. 3 for a COM port on Windows, /dev/ttyATH0 for Arduino Yun, /dev/ttyACM0 for Serial-over-USB on RaspberryPi.')

   parser.add_argument("--web", type = int, default = 8000,
                       help = 'Web port to use for embedded Web server. Use 0 to disable.')

   parser.add_argument("--router", type = str, default = u"ws://54.148.239.89:8080/ws",
                       help = 'If given, connect to this WAMP router. Else run an embedded router on 8080.')

   args = parser.parse_args()

  
   from twisted.python import log
   log.startLogging(sys.stdout)


   from twisted.internet import reactor
   print("Using Twisted reactor {0}".format(reactor.__class__))




   ## create embedded web server for static files
   ##
   if args.web:
      from twisted.web.server import Site
      from twisted.web.static import File
      reactor.listenTCP(args.web, Site(File(".")))


   ## run WAMP application component
   ##
   from autobahn.twisted.wamp import ApplicationRunner
   router = args.router or 'ws://localhost:8080'

   runner = ApplicationRunner(url=router, realm=u"realm1",
      extra = {'port': args.port, 'baudrate': args.baudrate, 'debug': args.debug})
   

   ## start the component and the Twisted reactor ..
   ##
   runner.run(McuComponent)
